package algorithm;

import java.util.Arrays;

/**
 * @Description: 插入排序
 * @Author: hmm
 * @CreateDate: 2019/8/27
 * @UpdateUser:
 * @UpdateDate: 2019/8/27
 * @UpdateRemark: 修改备注
 * @Version: 1.0
 */
public class InsertSort {

    public static void insertionSort(int[] array) {
        if (array.length == 0) {
            return;
        }
//        int current;
//        for (int i = 1; i < array.length; i++) {
//            current = array[i];
//            int preIndex = i - 1;
//            while (preIndex >= 0 && current < array[preIndex]) {
//                array[preIndex + 1] = array[preIndex];
//                preIndex--;
//            }
//            array[preIndex + 1] = current;
//        }
        for (int i = 1; i < array.length; i++) {
            for (int j = i - 1; j >= 0 && array[j + 1] < array[j]; j--) {
                swap(array, j, j + 1);
            }
        }
    }

    private static void swap(int[] array, int i, int j) {
        int temp = array[j];
        array[j] = array[i];
        array[i] = temp;
    }

    public static void main(String[] args) {
        int[] arr = {1, 6, 2, 41, 11, 25, 8, 31, 25, 22};
        insertionSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
